package com.best.util;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @author Jiang Akang
 * employeeId: BG435424
 * @date 2021/5/30
 **/

// 增强的类
@Aspect // 生成代理对象
@Component
public class LogUtil {

    @Pointcut("execution(* *(..))")
    public void myPointCut(){}

    // 前置通知
    @Before(value = "myPointCut()")
    @Order(1)
    public int before(JoinPoint joinPoint) {
        // 获取方法签名
        Signature signature = joinPoint.getSignature();
        // 获取参数信息
        Object[] args = joinPoint.getArgs();
        System.out.println("log---before: " + signature.getName() + "方法执行: 参数是" + Arrays.asList(args));
        return 100;
    }

    // 后置通知(返回通知)
    @AfterReturning(value = "myPointCut()", returning = "result")
    @Order(2)
    public void afterReturning(JoinPoint joinPoint, Object result) {
        Signature signature = joinPoint.getSignature();
        System.out.println("log---afterReturning: " + signature.getName() + "方法执行结束，结果是: " + result);
    }

    // 最终通知
    @After("myPointCut()")
    @Order(3)
    public void after(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        System.out.println("log---after: " + signature.getName() + "方法执行结束");
    }

    // 异常通知
    @AfterThrowing(value = "myPointCut()", throwing = "e")
    @Order(4)
    public void afterThrowing(JoinPoint joinPoint, Exception e) {
        Signature signature = joinPoint.getSignature();
        System.out.println("log---afterThrowing: " + signature.getName() + "方法抛出异常: " + e.getMessage());
    }

    @Around("myPointCut()")
    @Order(5)
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        Signature signature = pjp.getSignature();
        Object[] args = pjp.getArgs();
        Object result = null;
        try {
            System.out.println("log---around---start: " + signature.getName() + "方法执行");
            // 通过反射的方式调用目标的方法，相当于执行method.invoke()，可以自己修改结果值
            result = pjp.proceed(args);
            // result = 100;
            System.out.println("log---around---stop: " + signature.getName() + "方法执行结束");
        } catch (Throwable throwable) {
            System.out.println("log---around---异常: " + signature.getName() + "出现异常");
            throw throwable;
        } finally {
            System.out.println("log---around---返回: " + signature.getName() + "返回结果: " + result);
        }
        return result;
    }
}
